#include "colorpicker.h"
#include <QPainter>
#include <QColorDialog>

#include <stdio.h>

QColor convert (const ceColor4f& color)
{
  return QColor (color.r * 0xff,
                 color.g * 0xff,
                 color.b * 0xff,
                 color.a * 0xff);
}


ceColor4f convert (const QColor& color)
{
  return ceColor4f (color.red() / 255.0f,
                    color.green() / 255.0f,
                    color.blue() / 255.0f,
                    color.alpha() / 255.0f);
}

ColorPicker::ColorPicker(QWidget *parent)
  : QWidget(parent)
{
  SetColor (ceColor4f (1.0f, 1.0f, 1.0f, 1.0f));

  setMinimumSize(24, 24);
}

void ColorPicker::SetColor(const ceColor4f color)
{
  _color = color;

  repaint();
}

const ceColor4f& ColorPicker::GetColor() const
{
  return _color;
}


void ColorPicker::paintEvent (QPaintEvent *event)
{
  QPainter p (this);
  p.fillRect(frameGeometry(), convert (_color));

  QWidget::paintEvent (event);
}


void ColorPicker::mouseReleaseEvent(QMouseEvent *)
{
  QColor color = QColorDialog::getColor(convert (_color), this, "Color",
                                        QColorDialog::ShowAlphaChannel);
  if (color.isValid())
    {
      SetColor(convert (color));
      emit changed ();
    }
}
